package com.hnust.service.impl;

import com.hnust.dao.*;
import com.hnust.domain.AlternativeAnswer;
import com.hnust.domain.record.AlternativeAnswerRecord;
import com.hnust.domain.record.NewQuestionRecord;
import com.hnust.service.UpLoadService;
import com.hnust.util.IDUtil;
import com.hnust.util.PictureIO;
import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.collections.ParagraphCollection;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Service
public class UpLoadServiceImpl implements UpLoadService {

	@Autowired
	CourseTargetDao courseTargetDao;
	@Autowired
	QuestionTypeDao questionTypeDao;
	@Autowired
    ChapterDao capterDao;
	@Autowired
	QuestionDao questionDao;
	@Autowired
	AlternativeAnswerDao alternativeAnswerDao;

	String imageName = "rBgblWGmFeGAfb96AADcw93_3ec263.jpg";
	String upImageName = "fastdfs.jpg";
	String imagePath = "e://";

	/**
	 * @Author Tonited
	 * @Description //TODO 读取题目文件并返回题目列表
	 * @Date 17:42 2020/10/30
	 * @Param [file, courseId]
	 * @return java.util.Map<java.lang.String,java.lang.Object>
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
	public Map<String, Object> readQuestions(MultipartFile file, String courseId) throws Exception {
		String filePath = "";
		List<NewQuestionRecord> list = new ArrayList<>();
		try{
			filePath = upload(file);
		} catch (Exception e) {
			throw new Exception( "文件上传失败："+e.getMessage());
		}
		Document document = new Document(filePath);
		document.loadFromFile(filePath);

		//图片全部转存，并转换成html形式
		PictureIO.doPic(document);

		int nowQue = 0;
		int typeInt = 0;
		int easyChoose = 0;
		//答案列表
		List<AlternativeAnswerRecord> ansList = null;
		try {
			//根据课程代码获取专业ID
			Section section = document.getSections().get(0);
			ParagraphCollection paragraphs = section.getParagraphs();

			//对于每一段存储数据
			for (int j =0; j < section.getParagraphs().getCount(); ) {
				nowQue++;
				//读取题目元数据
				String queMetaDataString = paragraphs.get(j++).getText().replace("[","").replace("]","");
				String[] queMetaData = queMetaDataString.split(";");
				if(queMetaData.length<=1){
					queMetaData = queMetaDataString.split("；");
				}
				//获取题目类型信息
				String type = queMetaData[0].trim();
				if(type.contains("选")){
					typeInt = 2;
				}else if(type.contains("填")){
					typeInt=3;
				}else{//简答题
					typeInt=4;
				}
				String typeId = questionTypeDao.getQeuTypIdByQueTyp(typeInt);

				//获取题目难易度信息
				String easy = queMetaData[1].trim();
				if(easy.contains("简") || easy.contains("易")){
					easyChoose = 1;
				}else if(easy.contains("中")){
					easyChoose=2;
				}else{//困难题
					easyChoose=3;
				}

				//获取课程目标信息
				String couTarNum = queMetaData[2].trim();//课程目标
				String courseTargetId = courseTargetDao.getCouTarIdByNumAndCourseId(couTarNum,courseId);
				if(courseTargetId==null){
					throw new Exception("第"+nowQue+"题的"+"课程目标代码不存在");
				}

				//获取章节号
				String[] capter = queMetaData[4].trim().split("\\.");
				if (capter.length < 4) {
					throw new Exception("第"+nowQue+"题的"+"章节格式错误");
				}
				String capId = capterDao.getCapIdByCapNum(courseId, Integer.parseInt(capter[0]), Integer.parseInt(capter[1]), Integer.parseInt(capter[2]), Integer.parseInt(capter[3]));
				if (capId == null) {
					throw new Exception("第"+nowQue+"题的"+"章节不存在");
				}

				//获取知识点
				String point = queMetaData[3].trim();

				//获取题目内容
				StringBuilder content = new StringBuilder();
				while(!paragraphs.get(j).getText().isEmpty() && j < section.getParagraphs().getCount()-1){
					String rowContant = "<p>" + paragraphs.get(j).getText().replace(" ","&nbsp").replace("&778604985"," ") +"</p>";
					content.append(rowContant);
					j++;
				}
				j++;//跳过空行


				//获取解析
				j++;//跳过”解析:“
				String analyse = "";
				while(!paragraphs.get(j).getText().isEmpty() && j < section.getParagraphs().getCount()-1){
					analyse += "<p>" + paragraphs.get(j).getText().replace(" ","&nbsp").replace("&778604985"," ") +"</p>";
					j++;
				}
				j++;//跳过空行
				j++;//跳过 答案：
				ansList = new ArrayList<>();
				while(!paragraphs.get(j).getText().isEmpty() && j < section.getParagraphs().getCount()-1){
					String rowContent = paragraphs.get(j).getText();

					//如果是选择题
					if(type.contains("选")) {
						if(rowContent.isEmpty()){
							j+=2;
							break;
						}
						String[] nowAns = rowContent.split(" ");
						if (nowAns.length < 2) {
							throw new Exception("第"+nowQue+"题的"+"答案数据异常");
						}
						if (nowAns[nowAns.length - 1].contains("是")) {
							AlternativeAnswerRecord newAnswer = new AlternativeAnswerRecord(IDUtil.getPrimaryKey(), 1, "<p>"+nowAns[0].trim().replace(" ","&nbsp").replace("&778604985"," ")+"</p>");
							ansList.add(newAnswer);
						} else {
							AlternativeAnswerRecord newAnswer = new AlternativeAnswerRecord(IDUtil.getPrimaryKey(), 2, "<p>"+nowAns[0].trim().replace(" ","&nbsp").replace("&778604985"," ")+"</p>");
							ansList.add(newAnswer);
						}
					} else{ //如果是简答题填空题
						char[] rowContentChars = rowContent.toCharArray();
						if(Character.isDigit(rowContentChars[0]) || Character.isLetter(rowContentChars[0])){
							if(rowContentChars.length>1){
								if(rowContentChars[1]=='、' || rowContentChars[1]==' '){
									rowContentChars[0] = ' ';
									rowContentChars[1] = ' ';
									rowContent = String.valueOf(rowContentChars);
								}
							}
							rowContent = rowContent.trim();
						}
						AlternativeAnswerRecord newAnswer = new AlternativeAnswerRecord(IDUtil.getPrimaryKey(), 1, "<p>"+rowContent.replace(" ","&nbsp").replace("&778604985"," ")+"</p>");
						ansList.add(newAnswer);
					}
					j++;
				}
				list.add(new NewQuestionRecord(IDUtil.getPrimaryKey(),easyChoose, content.toString(),analyse,point,courseId,capId,typeId,ansList,courseTargetId));
				j++;//跳过一个空行
				j++;//跳过两个空行
				// 题目插入
			}
			//上传同时添加入数据库题目及其答案
//			for(NewQuestionRecord questionRecord : list){
//				questionDao.insertQuestion(questionRecord.getQueId(),
//						questionRecord.getLevel(),
//						questionRecord.getContent(),
//						questionRecord.getAnalysis(),
//						questionRecord.getPoint(),
//						courseId,
//						questionRecord.getChaId(),
//						questionRecord.getQueTypId(),
//						questionRecord.getCouTarId());
//				for(AlternativeAnswerRecord alternativeAnswerRecord : questionRecord.getAnswerList()) {
//					alternativeAnswerDao.addAnswer(questionRecord.getQueId(),alternativeAnswerRecord.getContent(),alternativeAnswerRecord.getRight(),alternativeAnswerRecord.getAltAnsId());
//				}
//			}
		}catch (Exception e){

			if("class org.springframework.dao.DuplicateKeyException".equals(e.getClass().toString())) {
				throw new Exception( "第"+nowQue+"题的"+"数据已存在");
			} else {
				throw new Exception("文件读取失败：格式错误-"+e.getMessage()+" 问题可能发生在第"+nowQue+"组数据");
			}
		}
		File willDeleteFile = new File(filePath);
		if(!willDeleteFile.delete()){
			throw new Exception("文件删除失败");
		}
		Map<String, Object> result = new TreeMap<>();
		result.put("msg","成功");
		result.put("list",list);
		return result;
	}

	/**
	 * @Author Tonited
	 * @Description //TODO 上传文件，判断文件是否符合规范，最终返回上传文件的路径
	 * @Date 16:31 2020/10/29
	 * @Param [file]
	 * @return java.lang.String
	 */
	@Override
	public String upload(MultipartFile file) throws Exception {
		// 获取文件名
		String fileName = file.getOriginalFilename();
		// 获取文件的后缀名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		if(!".docx".equals(suffixName) && !".doc".equals(suffixName)) {
			throw new Exception("文件不符合规范");
		}
		// 文件上传后的路径
		String filePath = System.getProperty("user.dir") + "/assets/upload/";
		File dest = new File(filePath + fileName);
		// 检测是否存在目录
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		file.transferTo(dest);

		return dest.getAbsolutePath();
	}

}